package com.glut.library.controller;

import com.glut.library.entity.Book;
import com.glut.library.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 *
 * 管理端图书馆里控制器
 * @author stubborn
 * @since 2024-12-13 16:28
 */

@RestController
@RequestMapping("/allbook")
public class BookManagementController {

    @Autowired
    private IBookService bookService;


    @PostMapping("/add")
    public ResponseEntity<String> createBook(@RequestBody Book book) {
        try {
            bookService.save(book);
            return ResponseEntity.status(HttpStatus.CREATED).body("书籍创建成功: " + book.getBookName());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("书籍创建失败: " + e.getMessage());
        }
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<String> updateBook(@PathVariable Integer id, @RequestBody Book book) {
        try {
            book.setId(id);
            boolean isUpdated = bookService.updateById(book);
            if (isUpdated) {
                return ResponseEntity.ok("书籍更新成功: " + book.getBookName());
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到该书籍，ID: " + id);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("书籍更新失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteBook(@PathVariable Integer id) {
        try {
            boolean isRemoved = bookService.removeById(id);
            if (isRemoved) {
                return ResponseEntity.ok("书籍删除成功，ID: " + id);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("未找到该书籍，ID: " + id);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("书籍删除失败: " + e.getMessage());
        }
    }
}